package cn.ty.acl.util;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.RandomStringUtils;

/**
 *	加解密
 *
 * @author summit
 * @since 2021/7/23 16:07
 */
public class CipherUtils {
	/**
	 * ECB 加密模式 文本拆分加密
	 * PKCS5Padding 数据块为8位，不够就填充
	 */
	public static final String AES_ALGORITHM = "AES/ECB/PKCS5Padding";

	/**
	 *
	 * DES 必须要是8字节
	 * AES 16字节
	 */
	public static String aesDecrypt(String data, String decryptKey)
			throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException,
			IllegalBlockSizeException, InvalidKeyException {
		byte[] byteData = Base64.getDecoder().decode(data);
		Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
		byte[] decryptedData = cipher.doFinal(byteData);

		return new String(decryptedData);
	}

	/**
	 * aes 加密
	 */
	public static String aesEncrypt(String data, String encryptKey)
			throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
			BadPaddingException, IllegalBlockSizeException {
		Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));

		byte[] byteData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));

		return Base64.getEncoder().encodeToString(byteData);
	}


	public static void main(String[] args) throws NoSuchPaddingException, BadPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidKeyException {

		//String decryptKey = "11111111111111";
		String decryptKey = RandomStringUtils.randomAlphanumeric(16);
		String data = "12345sdasdasdssssssssssssssssssssssssssssssssssssssssssssssssdaaaaaaaaaaaaaaaaaaaaaaaaaa6";
		String ret = aesEncrypt(data, decryptKey);
		String ret1 = aesEncrypt(data, decryptKey);
		System.out.println("两次加密结果：" + ret.equals(ret1));


//		System.out.println(ret.equals("n6HNK8XSTzo/gZQ/EJVy56SGcGaiZMckX7aJfJhb60qkhnBmomTHJF+2iXyYW+tKhgtBOeUKCyQRxa8S4CCAOmPPkVY3XWrMyCr27THsO7LT66HTdn1vr8AmyC2McmkF\n"));

		System.out.println(ret);
		String origin = aesDecrypt(ret, decryptKey);
		System.out.println(origin);
		System.out.println(origin.equals(data));
	}
}
